package 剑指Offer.中等;

/**
 * @author caihe
 * @date 2022/10/11 16:59
 */
public class _36二叉搜索树与双向链表 {

    Node head, pre;
    
    public Node treeToDoublyList(Node root) {
        if (root == null) {
            return null;
        }
        dfs(root);
        head.left = pre;
        pre.right = head;
        
        return head;
    }
    
    // 采用中序遍历
    void dfs(Node cur) {
        if (cur == null) {
            return;
        }
        dfs(cur.left);
        // 第一次到达最左叶子节点 设置head和pre
        if (pre != null) {
            pre.right = cur;
        } else {
            head = cur;
        }
        cur.left = pre;
        pre = cur;
        dfs(cur.right);
    }
    
    


    static class Node {
        public int val;
        public Node left;
        public Node right;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }
        
        public Node(int _val,Node _left,Node _right) {
            val = _val;
            left = _left;
            right = _right;
        }
    }
}
